package com.atguigu.srb.sms.controller.api;

import com.atguigu.common.exception.Assert;
import com.atguigu.common.result.R;
import com.atguigu.common.result.ResponseEnum;
import com.atguigu.common.utils.RandomUtils;
import com.atguigu.common.utils.RegexValidateUtils;
import com.atguigu.srb.sms.client.CoreUserInfoClient;
import com.atguigu.srb.sms.service.SmsService;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/sms")
@Api(tags = "短信管理")
public class ApiSmsController {

    @Autowired
    private SmsService smsService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private CoreUserInfoClient coreUserInfoClient;

    @GetMapping("/send/{mobile}")
    public R send(@PathVariable String mobile) {

        Assert.notEmpty(mobile, ResponseEnum.MOBILE_NULL_ERROR);
        Assert.isTrue(RegexValidateUtils.checkCellphone(mobile),ResponseEnum.MOBILE_ERROR);

        // 判断是否已被注册
        R r = coreUserInfoClient.checkMobile(mobile);
        boolean isExist = (boolean) r.getData().get("isExist");
        Assert.isTrue(isExist == false,ResponseEnum.MOBILE_EXIST_ERROR);

        // 发送验证码
        Map<String,Object> map = new HashMap<>();
        String code = RandomUtils.getFourBitRandom();
        map.put("code", code);
        // smsService.send(mobile, SmsProperties.TEMPLATE_CODE,map);

        // 将验证码保存到redis
        redisTemplate.opsForValue().set("sms:code:"+mobile,code,5, TimeUnit.MINUTES);

        return R.ok().message("发送短信成功");
    }
}
